package com.game.chinesechess.slice;

import com.game.chinesechess.Drawer;
import com.game.chinesechess.GameAbility;
import com.game.chinesechess.GameInfo;
import com.game.chinesechess.ResourceTable;
import com.game.chinesechess.check.rangeSense;
import com.game.chinesechess.devices.DeviceSelectDialog;
import com.game.chinesechess.piece.chess;
import com.game.chinesechess.util.Point;
import com.game.chinesechess.util.information;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.IDialog;
import ohos.data.distributed.common.*;
import ohos.data.distributed.user.SingleKvStore;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class GameAbilitySlice extends AbilitySlice {
    private static final String STROE_ID = "data";
    private static final HiLogLabel TAG = new HiLogLabel(HiLog.LOG_APP,0x12345,"signal");
    private Text text;
    private DependentLayout canvas;
    private static Boolean isLocal;
    private Drawer drawer;
    private KvManager kvManager;
    private SingleKvStore kvStore;
    private GameInfo info;
    private Timer checkTime,updateTime;
    private static String a="";
    private static String str1;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_game);
        isLocal=intent.getBooleanParam("isLocal",true);
        info=new GameInfo();
        info.color= chess.Color.RED;
        str1="你是红方,";
        if(!isLocal) {
            info.color = chess.Color.BlACK;
            str1="你是黑方,";
        }
        info.i=new GameInfo.I() {
            @Override
            public void saveMove(information information) {
                kvStore.putString("MOVE"+!isLocal,information.toJson());
            }
        };
        initUI();
        initDraw();
        initDataBase();
        checkOver();
        updateText();
        DeviceSelectDialog dialog = new DeviceSelectDialog(GameAbilitySlice.this);
        dialog.setListener(deviceIds -> {
            if (deviceIds != null && !deviceIds.isEmpty()) {
                startRemoteFas(deviceIds);
                kvStore.sync(deviceIds,SyncMode.PUSH_ONLY);
            }
            dialog.destroy();
        });
        if(isLocal){
            dialog.show();
        }
    }

    public void initUI(){
        text=(Text)findComponentById(ResourceTable.Id_tittle);
        text.setText(str1);
        canvas=(DependentLayout)findComponentById(ResourceTable.Id_canvas);
    }

    public  void initDraw(){
        drawer=new Drawer(this,true);
        drawer.setDrawParams(info);
        canvas.addComponent(drawer);
        drawer.setText(text);
    }

    public void initDataBase(){
        KvManagerConfig config=new KvManagerConfig(this);
        kvManager = KvManagerFactory.getInstance().createKvManager(config);
        Options options = new Options();
        options.setCreateIfMissing(true).setEncrypt(false).setKvStoreType(KvStoreType.SINGLE_VERSION);
        kvStore=kvManager.getKvStore(options,STROE_ID);
        subscribeDb(kvStore);
    }

    private void subscribeDb(SingleKvStore singleKvStore) {//订阅
        class KvStoreObserveClient implements KvStoreObserver {
            @Override
            public void onChange(ChangeNotification notification) {
                if(getString()!=null&&!a.equals(getString())){
                    Point begin=information.getStartPoint(getString());
                    Point end=information.getEndPoint(getString());
                    info.moveChess(begin.x, begin.y, end.x, end.y,false);
                    getUITaskDispatcher().asyncDispatch(new Runnable() {
                        @Override
                        public void run() {
                            drawer.drawChess();
                        }
                    });
                    a=getString();
                }
            }
        }
        KvStoreObserver kvStoreObserverClient = new KvStoreObserveClient();
        singleKvStore.subscribe(SubscribeType.SUBSCRIBE_TYPE_ALL,kvStoreObserverClient);
    }

    private String getString() {
        try {
            return  kvStore.getString("MOVE"+isLocal);
        } catch (KvStoreException exception) {
            HiLog.info(TAG,"String error" + exception.getMessage());
            return null;
        }
    }
    private void startRemoteFas(List<String> deviceIds) {
        Intent[] intents = new Intent[deviceIds.size()];
        for (int i = 0; i < deviceIds.size(); i++) {
            Intent intent = new Intent();
            intent.setParam("isLocal", false);
            Operation operation = new Intent.OperationBuilder()
                    .withDeviceId(deviceIds.get(i))
                    .withBundleName(getBundleName())
                    .withAbilityName(GameAbility.class.getName())
                    .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
                    .build();
            intent.setOperation(operation);
            intents[i] = intent;
        }
        startAbilities(intents);
    }

    public void checkOver(){
        checkTime=new Timer();
        checkTime.schedule(new TimerTask() {
            @Override
            public void run() {
                getUITaskDispatcher().asyncDispatch(new Runnable() {
                    @Override
                    public void run() {
                        if(rangeSense.isOver(info)){
                            checkTime.cancel();
                            updateTime.cancel();
                            CommonDialog dialog=new CommonDialog(GameAbilitySlice.this);
                            dialog.setTitleText("游戏结束");
                            if(info.color!=info.Winner){
                                dialog.setContentText("你输了！");
                                text.setText(str1+"你输了！");}
                            else{
                                dialog.setContentText("你赢了！");
                                text.setText(str1+"你赢了！");
                            }
                            dialog.setButton(IDialog.BUTTON3, "CONFIRM", (iDialog, i) -> iDialog.destroy());
                            dialog.show();
                        }
                    }
                });
            }
        },5,5);
    }

    public void updateText(){
        updateTime=new Timer();
        updateTime.schedule(new TimerTask() {
            @Override
            public void run() {
                String str="";
                if(info.turn== chess.Color.RED)
                    str="现在由红方行棋";
                else
                    str="现在由黑方行棋";
                String finalStr = str;
                getUITaskDispatcher().asyncDispatch(new Runnable() {
                    @Override
                    public void run() {
                        text.setText(str1+ finalStr);
                    }
                });
            }
        },1,5);
    }
    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

}
